const express = require('express');
const path = require('path');
const fs = require('fs');
const util = require('util')

const app = express();

const readFile = util.promisify(fs.readFile)
const writeFile = util.promisify(fs.writeFile)

app.all('*', (req, res, next) => {
    res.header('Access-Control-Allow-Origin', '*');
    res.header('Access-Control-Allow-Headers', 'Content-Type');
    res.header('Access-Control-Allow-Credentials', 'true');
    res.header('Access-Control-Allow-Methods', '*');
    if (req.method.toLowerCase() === 'options')
        res.send(200);
    else
        next();
});

app.use(express.static(path.join(__dirname, 'public')));
app.use(express.urlencoded({extended: false}));
app.use(express.json({}));
const cache = new Map();
app.get('/api/order/get', (req, res) => {
    const key = req.query.key;
    if (cache.has(key)) {
        const order = cache.get(key);
        cache.delete(key);
        res.json({order});
    } else {
        res.json({});
    }
})
app.post('/api/order/set', (req, res) => {
    const order = req.body;
    cache.set(order.key, order);
    res.json({msg: 'ok'})
})
app.get('/api/order/config', (req, res, next) => {
    if (cache.has('config')) {
        res.json(cache.get('config'));
    } else {
        readFile(path.join(__dirname, 'data/config.json'))
            .then((buffer) => JSON.parse(buffer.toString('utf8')))
            .then(config => {
                cache.set('config', config);
                res.json(config);
            })
            .catch(next)
    }
})
app.post('/api/order/config', (req, res, next) => {
    cache.set('config', req.body);
    writeFile(path.join(__dirname, 'data/config.json'), JSON.stringify(req.body, null, 4))
        .then(() => res.json({'msg': '设置成功'}))
        .catch(next)
})
app.listen(31023, () => {
    console.log('Server start on 31023')
});
